package com.google.rpc;


import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

//网络传输过程
public class RPCNetTransport {

    String host;
    int port;

    public RPCNetTransport(String host , int port) {
        this.host = host;
        this.port = port;
    }
    private Socket newSocket(){
        System.out.println("begin create Socket connect");
        Socket socket=null;
        try {
            socket=new Socket(host,port);
        }catch (Exception e){
            throw new RuntimeException("bulid connect failed ");
        }
        return socket;
    }
    public Object send(RPCRequest request) throws IOException {
        Socket socket=null;
        try {
            socket=newSocket();
            ObjectOutputStream outputStream=new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(request);
            outputStream.flush();


            ObjectInputStream inputStream=new ObjectInputStream(socket.getInputStream());
            Object result=inputStream.readObject();//反序列化得到结果
            inputStream.close();
            outputStream.close();
            return result;
        }catch (Exception e){
              throw new RuntimeException("send request exception:"+e);
        }finally {
            if(socket!=null){
                socket.close();
            }
        }
    }
}
